using System;
using System.Net;
using System.Text;

namespace Admin.NET.Application.GuangHeMeter;

/// <summary>
/// 动态缓存管理
/// </summary>
public class DynamicBufferManager
{
	/// <summary>
	/// 存放内存的数组
	/// </summary>
	public byte[] Buffer { get; set; }

	/// <summary>
	/// 写入数据大小
	/// </summary>
	public int DataCount { get; set; }

	/// <summary>
	/// 构造函数
	/// </summary>
	/// <param name="bufferSize"></param>
	public DynamicBufferManager(int bufferSize)
	{
		DataCount = 0;
		Buffer = new byte[bufferSize];
	}

	/// <summary>
	/// 获得当前写入的字节数
	/// </summary>
	/// <returns></returns>
	public int GetDataCount()
	{
		return DataCount;
	}

	/// <summary>
	/// 获得剩余的字节数
	/// </summary>
	/// <returns></returns>
	public int GetReserveCount()
	{
		return Buffer.Length - DataCount;
	}

	public void Clear()
	{
		DataCount = 0;
		Buffer = new byte[4096];
	}

	/// <summary>
	/// 清理指定大小的数据
	/// </summary>
	/// <param name="count"></param>
	public void Clear(int count)
	{
		if (count >= DataCount)
		{
			DataCount = 0;
			return;
		}
		for (int i = 0; i < DataCount - count; i++)
		{
			Buffer[i] = Buffer[count + i];
		}
		DataCount -= count;
	}

	/// <summary>
	/// 设置缓存大小
	/// </summary>
	/// <param name="size"></param>
	public void SetBufferSize(int size)
	{
		if (Buffer.Length < size)
		{
			byte[] tmpBuffer = new byte[size];
			Array.Copy(Buffer, 0, tmpBuffer, 0, DataCount);
			Buffer = tmpBuffer;
		}
	}

	/// <summary>
	/// 写入数据
	/// </summary>
	/// <param name="buffer"></param>
	/// <param name="offset"></param>
	/// <param name="count"></param>
	public void WriteBuffer(byte[] buffer, int offset, int count)
	{
		if (GetReserveCount() >= count)
		{
			Array.Copy(buffer, offset, Buffer, DataCount, count);
			DataCount += count;
			return;
		}
		int totalSize = Buffer.Length + count - GetReserveCount();
		byte[] tmpBuffer = new byte[totalSize];
		Array.Copy(Buffer, 0, tmpBuffer, 0, DataCount);
		Array.Copy(buffer, offset, tmpBuffer, DataCount, count);
		DataCount += count;
		Buffer = tmpBuffer;
	}

	/// <summary>
	/// 写入数据
	/// </summary>
	/// <param name="buffer"></param>
	public void WriteBuffer(byte[] buffer)
	{
		WriteBuffer(buffer, 0, buffer.Length);
	}

	public void WriteShort(short value, bool convert)
	{
		if (convert)
		{
			value = IPAddress.HostToNetworkOrder(value);
		}
		byte[] tmpBuffer = BitConverter.GetBytes(value);
		WriteBuffer(tmpBuffer);
	}

	public void WriteInt(int value, bool convert)
	{
		if (convert)
		{
			value = IPAddress.HostToNetworkOrder(value);
		}
		byte[] tmpBuffer = BitConverter.GetBytes(value);
		WriteBuffer(tmpBuffer);
	}

	public void WriteLong(long value, bool convert)
	{
		if (convert)
		{
			value = IPAddress.HostToNetworkOrder(value);
		}
		byte[] tmpBuffer = BitConverter.GetBytes(value);
		WriteBuffer(tmpBuffer);
	}

	public void WriteString(string value)
	{
		byte[] tmpBuffer = Encoding.UTF8.GetBytes(value);
		WriteBuffer(tmpBuffer);
	}
}
